<?php

namespace jzl;

use catcher\CatchResponse;
use GuzzleHttp\Exception\RequestException;
use houniao\tools\Params;
use think\Exception;
use think\helper\Str;

class Request
{
    protected $key='';

    protected $secret='';

    protected $host='';

    protected $passphrase='';


    protected $nonce='';
    protected $timestamp = '';

    protected $signature='';

    protected $headers=[];

    protected $type='';

    protected $path='';

    protected $data=[];

    protected $options=[];

    protected $platform='';

    protected $version='';

    protected $response_headers=[];

    public function __construct(array $data = [])
    {
        $this->data['key']= $data['app_key'] ?? 'JZL1ebf7e48a76bb5dd';
        $this->host= $data['host'] ?? 'https://www.jzl.com';
    }

    /**
     * 认证
     * */
    protected function auth(){
        $this->nonce();
//
        $this->signature();
//
        $this->headers();
//
        $this->options();

    }

    /**
     *
     * */
    protected function nonce(){
        $this->data['timestamp'] = time();
        $this->data['nonce_str']= Str::random(32);
    }

    /**
     * 签名
     * */
    protected function signature(){
        //dd($this->data);
        $this->data = Params::paraFilter($this->data);

        //对待签名参数数组排序
        $old = $this->data;
        $this->data = Params::argSort($this->data);

        //生成签名结果
        $mysign = Params::buildRequestMysign($this->data,$this->secret);

        //签名结果与签名方式加入请求提交参数组中

        $old['sign'] = $mysign;
        $this->data = $old;
        //$this->data =  array_merge($this->data,[$mysign]);
    }

    /**
     *
     * */
    protected function headers(){
        $this->headers=[
            'Content-Type' => 'application/json',
        ];

//        if(!empty($this->key) && !empty($this->secret)) {
//            $this->headers=array_merge($this->headers,[
//                'OK-ACCESS-KEY'=> $this->key,
//                'OK-ACCESS-TIMESTAMP'=>$this->nonce,
//                'OK-ACCESS-PASSPHRASE' =>$this->passphrase,
//                'OK-ACCESS-SIGN' => $this->signature,
//            ]);
//        }
    }

    /**
     *
     * */
    protected function options(){
        if(isset($this->options['headers'])) $this->headers=array_merge($this->headers,$this->options['headers']);

        $this->options['headers']=$this->headers;
        $this->options['timeout'] = $this->options['timeout'] ?? 60;
    }

    /**
     *
     * */
    protected function send(){
        $client = new \GuzzleHttp\Client();

        $url=$this->host.$this->path;

        if(!empty($this->data)) {
            if($this->type=='GET') {
                $url.='?'.http_build_query($this->data);
            }else{
                $this->options['body']=json_encode($this->data);
            }
        }
        /*print_r($this->options);
        die;*/
        $response = $client->request($this->type, $url, $this->options);

        $this->response_headers = $response->getHeaders();

        return $response->getBody()->getContents();
    }

    /*
     *
     * */
    protected function exec(){
        //$this->auth();

        try {
            $result = json_decode($this->send(),true);

            return $result;

//            if(0 ==$result['code']){
//                return $result;
//            }
//            throw new Exception($result['msg']);
        }catch (RequestException $e){
            if(empty($e->getResponse()) || $e->getResponse()==null)
                throw new Exception('接口请求失败，没有返回值');

            if(method_exists($e->getResponse(),'getBody')){
                $contents=$e->getResponse()->getBody()->getContents();

                $temp=json_decode($contents,true);
                if(!empty($temp)) {
                    $temp['_method']=$this->type;
                    $temp['_url']=$this->host.$this->path;
                }else{
                    $temp['_message']=$e->getMessage();
                }
            }else{
                $temp['_message']=$e->getMessage();
            }

            $temp['_httpcode']=$e->getCode();

//            throw new Exception(json_encode($temp));
            throw new Exception($e->getMessage());
        }
    }

    /**
     * Get Response Headers
     * */
    public function getResponseHeaders(){
        return $this->response_headers;
    }
}